import axios from "axios";
import { getToken } from "@/utils/auth";
import pinyinUtils from 'pinyin.js';


  /**
   * 防抖函数
   * @param {Function} fn 执行函数 
   * @param {Number} time 防抖时间
   * @returns 
   */
  export const debounce = (fn, time) => {
    let timer
    return function (...argu) {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(() => {
        fn(...argu)
        clearTimeout(timer)
        timer = null
      }, time)
    }
  }
/**
 * @name 获取时间
 */
export function getTime(n) {
  var now = new Date();
  var year = now.getFullYear();
  //因为月份是从0开始的,所以获取这个月的月份数要加1才行
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var day = now.getDay();
  console.log(date);
  //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
  if (day !== 0) {
    n = n + (day - 1);
  } else {
    n = n + day;
  }
  if (day) {
    //这个判断是为了解决跨年的问题
    if (month > 1) {
      month = month;
    }
    //这个判断是为了解决跨年的问题,月份是从0开始的
    else {
      year = year - 1;
      month = 12;
    }
  }
  now.setDate(now.getDate() - n);
  year = now.getFullYear();
  month = now.getMonth() + 1;
  date = now.getDate();
  // console.log(n);
  var s =
    year +
    "-" +
    (month < 10 ? "0" + month : month) +
    "-" +
    (date < 10 ? "0" + date : date);
  return s;
}
/**
 * @name 格林尼治时间转标准时间
 */
export function GMTToStr(time) {
  let date = new Date(time);
  let Str =
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) +
    "-" +
    (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) +
    " " +
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
    ":" +
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":" +
    (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
  return Str;
}
/**
 * @name 时间间隔
 */
export function timeSlot(step, start, end) {
  //  step = 间隔的分钟
  var date = new Date(
    new Date(new Date().toLocaleDateString()).getTime() -
      1000 * 60 * (24 * 60 - start)
  );
  var arr = [],
    timeArr = [];
  //此处24*60/step，获取的24个小时内有多少间隔。 将24改为12，则可获取12小时内的间隔
  var slotNum = (end - start) / step; // 算出多少个间隔
  for (var f = 0; f <= slotNum; f++) {
    //  stepM * f = 24H*60M
    // 获取：零点的时间 + 每次递增的时间
    var time = new Date(Number(date.getTime()) + Number(step * 60 * 1000 * f));
    var hour = "",
      sec = "";
    // 获取小时
    time.getHours() < 10
      ? (hour = "0" + time.getHours())
      : (hour = time.getHours());
    // 获取分钟
    time.getMinutes() < 10
      ? (sec = "0" + time.getMinutes())
      : (sec = time.getMinutes());
    timeArr.push(hour + ":" + sec);
  }
  return timeArr;
}
/**
 * @name 时间转数值
 */
export function timeChangeNum(time) {
  let newValue = time;
  newValue = newValue.split(":");
  newValue = Number(newValue[0]) * 60 + Number(newValue[1]);

  return newValue;
}
/**
 * @name 格式化时间
 */
export function formatDate(date) {
  if (date != null) {
    const dateMat = new Date(date);
    const year = dateMat.getFullYear();
    const month =
      dateMat.getMonth() + 1 < 10
        ? "0" + (dateMat.getMonth() + 1)
        : dateMat.getMonth() + 1;
    const day =
      dateMat.getDate() < 10 ? "0" + dateMat.getDate() : dateMat.getDate();
    const timeFormat = year + "-" + month + "-" + day;
    return timeFormat;
  }
}
/**
 * @name 数组扁平化
 */
export function flatArr(arr, newArr) {
  if (arr.length <= 0) {
    return;
  } else {
    for (let i = 0; i < arr.length; i++) {
      newArr.push(arr[i]);
      if (arr[i].children && arr[i].children.length > 0) {
        flatArr(arr[i].children, newArr);
      }
    }
    return newArr;
  }
}
/**
 * @name 树形数组过滤
 */
export function filterMultiDimensionalArray(arr, filterFunc) {
  return arr.filter((value) => {
    if (value.children && value.children.length > 0) {
      value.children = filterMultiDimensionalArray(value.children, filterFunc);
    }
    return filterFunc(value);
  });
}
/**
 * @name 菜单结点删除
 */
export function deletArrAttribute(arr, attribute = "children") {
  return arr.map((value) => {
    if (value.children && value.children.length > 0) {
      value.children = deletArrAttribute(value.children);
    } else if (value.children && value.children.length <= 0) {
      delete value[attribute];
    }
    return value;
  });
}
/**
 * @name 过滤数据的方法
 */
export function filterObject(obj) {
    let a = {};
    for (let key in obj) {
      // if (obj[key] != "") {
      //   a[key] = obj[key];
      //   } else  
        if (obj[key] === 0 || obj[key] === false) {
        a[key] = obj[key];
        }else if(Array.isArray(obj[key]) && obj[key].length>0){
          a[key] = obj[key];
        }else {
          a[key] = obj[key];
        }
    }
    return a;
}
/**
 * @name 同步导出
 * @param url 导出的url
 * @param method 导出的请求方式
 * @param fileName 文件名
 * @param query url参数
 * @param data requestBody参数
 */
export function exportFile(
  url,
  method = "get",
  fileName = "导出的文件",
  query = {},
  queryData = {}
) {
  return new Promise((a, b) => {
    axios({
      url: import.meta.env.VITE_APP_BASEURL + url,
      method: method,
      responseType: "blob",
      params: query,
      data: queryData,
      headers: { Authorization: `bearer ${getToken()}` },
    })
      .then((res) => {
        if (res.status == 200) {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          setTimeout(() => {
            a("下载成功");
          }, 2000);
        } else {
          b("下载失败");
        }
      })
      .catch(() => {
        b("下载失败");
      });
  });
}
/**
 * @name 去除重复数据
 * @param arr 数组
 * @param uniId 关键词
 */
export function uniqueFunc(arr, uniId) {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}
/** 
 * @name 天数转时间格式
 * @param beforeDay 需要转换的天数

*/
export function timeTransform(beforeDay) {
  let dateOne = new Date();
  dateOne.setDate(dateOne.getDate() - beforeDay);
  dateOne.toLocaleDateString(); //格式化时间
  let monthOne =
    dateOne.getMonth() + 1 < 10
      ? "0" + (dateOne.getMonth() + 1)
      : dateOne.getMonth() + 1;
  let yearOne = dateOne.getFullYear();
  let dayOne =
    dateOne.getDate() < 10 ? "0" + dateOne.getDate() : dateOne.getDate();
  return yearOne + "-" + monthOne + "-" + dayOne;
}
export function objectArraysAreEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }

  const stringifiedArr1 = JSON.stringify(arr1);
  const stringifiedArr2 = JSON.stringify(arr2);

  return stringifiedArr1 === stringifiedArr2;
}

/**
   * @description: 修改表格forms options配置
   * @param {array} source 源数据
   * @param {array} keys 需要修改的key
   * @param {array} values 修改的值 []
   */
export function changeOptions (source,keys,values){
  keys.forEach((key,index) => {
    const item = source.value.find(item => item.prop === key)
    if(item){
      item.data = values[index]
    }
  });
}

/**
 * @name 数字1转一
 */
function numberToChinese(number) {
  const chineseNumbers = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
    "十",
  ];

  if (number < 0 || number > 10) {
    return "不支持的数字范围";
  }

  return chineseNumbers[number];
}

export function convertToChinese(num) {
  if (num < 0 || num > 100) {
    return "不支持的数字范围";
  }

  if (num === 0) {
    return "零";
  }

  if (num <= 10) {
    return numberToChinese(num);
  }

  if (num === 100) {
    return "一百";
  }

  const tens = Math.floor(num / 10);
  const ones = num % 10;

  if (ones === 0) {
    return numberToChinese(tens) + "十";
  } else {
    return numberToChinese(tens) + "十" + numberToChinese(ones);
  }
}
// 扁平转树型
export const buildTree = (data)=>{
  const tree = {};

  // 创建一个以 id 为键的映射，方便通过 id 查找节点
  const map = {};
  data.forEach(node => {
    map[node.id] = { ...node, children: [] };
  });

  // 遍历数据，将每个节点添加到其父节点的 children 数组中
  data.forEach(node => {
    if (node.parentId != '0') {
      const parent = map[node.parentId];
      if (parent) {
        parent.children.push(map[node.id]);
      }
    } else {
      tree[node.id] = map[node.id];
    }
  });

  return Object.values(tree);
}


//判断一个对象是否为空对象
export function isEmptyObject(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
//获取基础设置字段并生成数组
export function getFieldValue(fieldName,arr = [],valueKey="attributeValue"){
  if(!fieldName || (!arr || arr.length<=0)){
    return [];
  }
  let classifyInfo =  arr.find(value=>value.attributeValue == fieldName) || "";

  if(classifyInfo){
    let newArr =  classifyInfo.secondConfigVOs.filter(item=>item.delFlag===0).map(lis=>{
      return {
          label:lis.attributeValue,
          value:lis[valueKey]
      }
    })
    return newArr;
  }else{
    return [];
  }
}
/**
 * 通过id获取特定的label
 * @param {array} ids id数组
 * @param {array} arr 源数组
 */
export function getLabelById(ids,arr){
  if(!ids || !arr || arr.length<=0 || ids.length<=0){
    return "";
  }
  return ids.map(item=> arr.find(f=> f.value==item)?.label).filter(item=>item).join(",");
}

/** 
 * @name 中文转拼音首字母
*/

export function generateInitials(str) {
  let initials = '';
  for (let i = 0; i < str.length; i++) {
    const char = str.charAt(i);
    if (/[\u4e00-\u9fa5]/.test(char)) {
      initials += getPinyinInitials(char);
    } else {
      initials += char;
    }
  }
  return initials;
}

function getPinyinInitials(char) {
  const pinyin = pinyinUtils(char);
  
  let initials = '';
  for (let i = 0; i < pinyin.length; i++) {
    if(pinyin[i] === 'ā'){
      pinyin[i] = 'a';
    }
    const initial = pinyin[i].charAt(0);

    if (/[a-zA-Z]/.test(initial)) {
      initials += initial.toUpperCase();
      break;
    }
  }
  return initials;
}


// 定义一个递归函数，用于构建树形结构
export function buildTrees(array, parentId = '0') {
  const tree = [];
  for (const item of array) {
    if (item.parentId === parentId) {
      const children = buildTrees(array, item.id);
      if (children.length > 0) {
        item.children = children;
      }else{
        item.children = []
      }
      tree.push(item);
    }
  }
  return tree;
}

// 树转扁平
export function flattenTree(tree) {
  const flattened = [];
  for (const node of tree) {
    flattened.push(node);
    if (node.children.length > 0) {
      const children = flattenTree(node.children);
      flattened.push(...children);
    }
  }
  return flattened;
}


export function limitFloat(value){
  let val = value.toString();
  val = val.match(/^\d*(\.?\d{0,2})/g)[0];
  if(val>999999999.99){
      val = val.split('.')
      if((val[1]??'') !== ''){
        val = [val[0].slice(0,9),val[1]].join('.');
      }else{
        val = val[0].slice(0,9);
      }
  }

  return val;
}

// 限制输入自定义最大值
export function limitMax(value,maxValue = 999999999.99){
  let val = value.toString();
  val = val.match(/^\d*(\.?\d{0,2})/g)[0];
    if(val>maxValue){
      val = maxValue
    }
  return val;
}


export function limitInt(value,limitLength = 9){
  let val = value;
  let bitLength = limitLength;

  val = val.replace(/\D/g, "");

  if(val.length>bitLength){
    val = val.split('.')
    val = val[0].slice(0,bitLength);
  }
  return val;
}
export function giveIntMin(value,minValue = 1){
  let val = value;
  if((val??'') !== ''){
    if(Number(val) === 0){
      val = minValue;
    }
  }
  return val;
}
export function giveFloatMin(value,minValue = 0.01){
  let val = value;
  if((val??'') !== ''){
    if(Number(val) === 0){
      val = minValue;
    }
  }
  return val
}
/**
 * 文本过滤器,为空的情况下返回'-'
 * @param {T} data
 */
export function textFilter(data) {
  if (data === null || data === undefined || data === '') {
    return '-';
  }
  return data;
}